package player

import (
	"base"
	. "gate_server/logic/internal"
	"gate_server/logic/player/event"
	"gate_server/model"
	"proto/base"
	"proto/server/gate"
)

type playerService struct {
}

func init() {
	service := new(playerService)

	Protocol.Register(new(proto_server_gate.OnLogin), service.onLogin)
	Protocol.Register(new(proto_server_gate.OnLogout), service.onLogout)
}

func (*playerService) onLogin(args []interface{}) {
	msg := args[0].(*proto_server_gate.OnLogin)
	//agent := args[1].(gate.Agent)
	base.Logger.Debug("player service on login, msg: %s", msg)

	var player *model.Player
	if msg.Code == proto_base.ErrorCode_Success {
		playerId := base.PlayerId(msg.PlayerId)
		var exists bool
		if player, exists = system.players[playerId]; !exists {
			serverId := base.AgentId(msg.GameId)
			player = model.NewPlayer(playerId, serverId)
			system.players[playerId] = player
		}
	}

	Event.Notify(player_event.OnLogin, msg, player)
}

func (*playerService) onLogout(args []interface{}) {
	msg := args[0].(*proto_server_gate.OnLogout)
	//agent := args[1].(gate.Agent)
	base.Logger.Debug("player service on logout, msg: %s", msg)

	playerId := base.PlayerId(msg.PlayerId)
	player, exists := system.players[playerId]
	if !exists {
		return
	}

	delete(system.players, playerId)
	Event.Notify(player_event.OnLogout, player, msg.Reason)
}
